import { Product, ProductService } from "@mallfoundry/catalog"
import { PageHeader } from "antd"
import * as _ from "lodash"
import * as React from "react"
import { useState } from "react"
import { useHistory, useParams } from "react-router-dom"
import { messageError } from "../../utils/reason"
import ProductForm from "./product-form"

import classes from "./product-new.module.scss"

export default function ProductNew() {
  const history = useHistory()
  const { storeId = "" } = useParams<{ storeId: string }>()
  const [loading, setLoading] = useState(false)
  const [product] = useState(_.assign(new Product(), { storeId }))

  function onFinish(newProduct: Product) {
    setLoading(true)
    ProductService.addProduct(newProduct)
      .then(product => history.push(`/stores/${product.storeId}/products/${product.id}`))
      .catch(messageError)
      .finally(() => setLoading(false))
  }

  return (
    <div className={classes.newProduct}>
      <PageHeader title="发布商品" ghost={false}/>
      <div className={classes.newProductContent}>
        <ProductForm loading={loading} product={product} onFinish={onFinish}/>
      </div>
    </div>
  )
}
